package com.business_clean.ui.fragment.addproject;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.TimeUtils;
import com.business_clean.app.App;
import com.business_clean.app.base.BaseFragment;
import com.business_clean.app.callback.OnDialogCityIdPickerListener;
import com.business_clean.app.callback.OnDialogCityPickerListener;
import com.business_clean.app.callback.OnDialogSelectListener;
import com.business_clean.app.callback.OnDialogTimePickerListener;
import com.business_clean.app.callback.OnNationListener;
import com.business_clean.app.callback.ProviceCityAreaDataCallBack;
import com.business_clean.app.config.AsyncRequestUtil;
import com.business_clean.app.config.ConstantMMVK;
import com.business_clean.app.ext.CommonUtils;
import com.business_clean.app.ext.LoadingDialogExtKt;
import com.business_clean.app.uitl.ChoosePicUtil;
import com.business_clean.app.uitl.GlideUtil;
import com.business_clean.app.uitl.MMKVHelper;
import com.business_clean.app.uitl.ToastUtil;
import com.business_clean.app.uitl.UploadFileHelper;
import com.business_clean.app.weight.dialog.CustomCityPickerPopup;
import com.business_clean.app.weight.dialog.CustomTimePickerPopup;
import com.business_clean.data.initconfig.city.ProviceCityAreaData;
import com.business_clean.data.mode.init.BaseIDNameEntity;
import com.business_clean.data.mode.members.IDCardMemberEntity;
import com.business_clean.data.mode.members.IdentityEntity;
import com.business_clean.data.mode.members.MembersDetailEntity;
import com.business_clean.data.mode.members.OCRIDCardInfoEntity;
import com.business_clean.databinding.FragmentIdCardBinding;
import com.business_clean.ui.activity.custom.AddProjectActivity;
import com.business_clean.ui.adapter.BaseStringAdapter;
import com.business_clean.viewmodel.request.ProjectMembersViewModel;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.luck.picture.lib.decoration.MyGridSpacingItemDecoration;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.lxj.xpopup.interfaces.OnSelectListener;

import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import me.hgj.mvvmhelper.ext.LogExtKt;

public class IdCardFragment extends BaseFragment<ProjectMembersViewModel, FragmentIdCardBinding> {

    private BaseStringAdapter sexAdapter;
    private BaseStringAdapter marriageAdapter;

    private String[] strings = {"拍照", "相册"};

    private int sexPosition;
    private int marriagePosition;

    private String homeTown;
    private String city;

    private String nation;
    private String nationId;
    private String cityId;

    private String id_card_front;

    private String uuid;

    private int type = 0;

    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        sexAdapter = new BaseStringAdapter(1);
        getMDatabind().recyclerSex.setLayoutManager(new GridLayoutManager(getMActivity(), 2));
        getMDatabind().recyclerSex.addItemDecoration(new MyGridSpacingItemDecoration(2, 20, true));
        getMDatabind().recyclerSex.setAdapter(sexAdapter);
        List<String> sexList = new ArrayList<>();
        sexList.add("男");
        sexList.add("女");
        sexAdapter.setList(sexList);

        //婚姻状态
        marriageAdapter = new BaseStringAdapter(1);
        getMDatabind().recyclerMarriage.setLayoutManager(new GridLayoutManager(getMActivity(), 3));
        getMDatabind().recyclerMarriage.addItemDecoration(new MyGridSpacingItemDecoration(3, 10, true));
        getMDatabind().recyclerMarriage.setAdapter(marriageAdapter);
        List<String> marriageList = new ArrayList<>();
        marriageList.add("已婚");
        marriageList.add("未婚");
        marriageList.add("离异");
        marriageAdapter.setList(marriageList);
        marriageAdapter.updateItem(0);

        getMDatabind().withIdCard.setInputIDCardNumber();

        getMDatabind().bottom.butBase.setText("下一步");
    }

    @Override
    public void lazyLoadData() {
        if (getArguments() != null) {//说明已经存在了
            uuid = getArguments().getString("uuid");
            String application_no = getArguments().getString("application_no");
            type = getArguments().getInt("type");
            HashMap<String, String> hashMap = new HashMap<>();
            if (!TextUtils.isEmpty(uuid)) {
                hashMap.put("uuid", uuid);
            }
            if (!TextUtils.isEmpty(application_no)) {
                hashMap.put("application_no", application_no);
            }
            hashMap.put("is_identity", "1");
            //1是草稿编辑  2是草稿新建 3是档案详情
            if (type == 3) {
                mViewModel.requestStaffDetail(hashMap);//真正的详情
            } else {
                mViewModel.requestMembersDetail(hashMap);//草稿的详情，还没真的成为员工
            }
        }
    }


    @Override
    public void initObserver() {
        App.appViewModelInstance.getCreateUuid().observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                uuid = s;//拿到这个 uuid 给当前的 uuid
            }
        });
    }

    @Override
    public void onBindViewClick() {
        sexAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                sexPosition = position;
                sexAdapter.updateItem(position);
            }
        });
        marriageAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
                marriagePosition = position;
                marriageAdapter.updateItem(position);
            }
        });
        getMDatabind().ivCard1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                CommonUtils.showBottomListWith(getActivity(), 20, "", strings, new OnSelectListener() {
                    @Override
                    public void onSelect(int position, String text) {
                        switch (position) {
                            case 0:
                                ChoosePicUtil.openCameraTake(getMActivity(), new OnResultCallbackListener<LocalMedia>() {
                                    @Override
                                    public void onResult(ArrayList<LocalMedia> result) {
                                        if (result.get(0).isCompressed()) {
                                            GlideUtil.loadPicRound(getMActivity(), result.get(0).getCompressPath(), getMDatabind().ivCard1, 0);
                                            uploadPic(result.get(0).getCompressPath());
                                        } else {
                                            GlideUtil.loadPicRound(getMActivity(), result.get(0).getRealPath(), getMDatabind().ivCard1, 0);
                                            uploadPic(result.get(0).getRealPath());
                                        }

                                    }

                                    @Override
                                    public void onCancel() {

                                    }
                                });
                                break;
                            case 1:
                                ChoosePicUtil.openAlbum(getMActivity(), 1, new OnResultCallbackListener<LocalMedia>() {
                                    @Override
                                    public void onResult(ArrayList<LocalMedia> result) {
                                        GlideUtil.loadPicRound(getMActivity(), result.get(0).getCompressPath(), getMDatabind().ivCard1, 0);
                                        uploadPic(result.get(0).getCompressPath());
                                    }

                                    @Override
                                    public void onCancel() {

                                    }
                                });
                                break;
                        }
                    }
                });

            }
        });

        //出生日期
        getMDatabind().withBirthday.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar defInstance = Calendar.getInstance();
                if (!TextUtils.isEmpty(getMDatabind().withBirthday.getTvRight())) {
                    defInstance.setTime(TimeUtils.string2Date(getMDatabind().withBirthday.getTvRight(), "yyyy-MM-dd"));
                }
                CommonUtils.showDialogTimePickerView(getMActivity(), "出生日期", defInstance, 0, 0, null, null, CustomTimePickerPopup.Mode.YMD, new OnDialogTimePickerListener() {
                    public void onTimeChanged(Date date) {
                    }

                    @Override
                    public void onTimeConfirm(Date date, View view) {
                        getMDatabind().withBirthday.setTvRightText(TimeUtils.date2String(date, "yyyy-MM-dd"));
                    }
                });
            }
        });


        //身份开始日期
        getMDatabind().withIdCardStartTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.showDialogTimePickerView(getMActivity(), "身份证开始日期", null, 0, 0, null, null, CustomTimePickerPopup.Mode.YMD, new OnDialogTimePickerListener() {
                    public void onTimeChanged(Date date) {
                    }

                    @Override
                    public void onTimeConfirm(Date date, View view) {
                        getMDatabind().withIdCardStartTime.setTvRightText(TimeUtils.date2String(date, "yyyy-MM-dd"));
                    }
                });
            }
        });

        //身份证到期日期
        getMDatabind().withIdCardEndTime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.showDialogTimePickerView(getMActivity(), "身份证结束日期", null, 0, 0, null, null, CustomTimePickerPopup.Mode.YMD, new OnDialogTimePickerListener() {
                    public void onTimeChanged(Date date) {
                    }

                    @Override
                    public void onTimeConfirm(Date date, View view) {
                        getMDatabind().withIdCardEndTime.setTvRightText(TimeUtils.date2String(date, "yyyy-MM-dd"));
                    }
                });
            }
        });


        //户籍城市
        getMDatabind().withCity1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CommonUtils.showDialogCityPickerView(getMActivity(), "请选择户籍城市", CustomCityPickerPopup.Mode.PC, homeTown, city, "", new OnDialogCityPickerListener() {
                    @Override
                    public void onCityConfirm(String province, String city0, String area, int options1, int options2, int options3, View v) {
                        homeTown = province;
                        city = city0;
                        getMDatabind().withCity1.setTvRightText(fillHomeTownAndCity(homeTown, city0, null));
                    }

                    @Override
                    public void onCityChange(String province, String city, String area) {

                    }
                }, new OnDialogCityIdPickerListener() {
                    @Override
                    public void onCityConfirm(String provinceId, String cityId0, String areaId) {
                        cityId = cityId0;
//                        ToastUtil.show(cityId0);
                    }
                });
            }
        });

        //民族列表
        getMDatabind().withNation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String cityDataJson = MMKVHelper.getString(ConstantMMVK.NATION_LIST);
                if (!TextUtils.isEmpty(cityDataJson)) {
                    List<BaseIDNameEntity> datas = JSON.parseArray(cityDataJson, BaseIDNameEntity.class);
                    showNationDialog(datas);
                } else {
                    AsyncRequestUtil.requestNationData(new OnNationListener() {
                        @Override
                        public void nationCallBack(List<BaseIDNameEntity> list) {
                            showNationDialog(list);
                        }
                    });
                }
            }
        });


        getMDatabind().bottom.butBase.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (TextUtils.isEmpty(id_card_front)) {
                    ToastUtil.show("请先上传身份证头像面");
                    return;
                }
                if (TextUtils.isEmpty(getMDatabind().withName.getInputText())) {
                    ToastUtil.show("请输入姓名");
                    return;
                }
                if (TextUtils.isEmpty(getMDatabind().withIdCard.getInputText())) {
                    ToastUtil.show("请输入身份证");
                    return;
                }

                if (sexAdapter.getSelectedIndices() == null || sexAdapter.getSelectedIndices().size() == 0) {
                    ToastUtil.show("请选择性别");
                    return;
                }

                if (TextUtils.isEmpty(nationId)) {
                    ToastUtil.show("请选择民族");
                    return;
                }

                if (getMDatabind().withBirthday.getTvRight().equals("请选择")) {
                    ToastUtil.show("请选择出生日期");
                    return;
                }

                if (getMDatabind().withCity1.getTvRight().equals("请选择")) {
                    ToastUtil.show("请选择户籍城市");
                    return;
                }


                HashMap<String, String> hashMap = new HashMap<>();
                hashMap.put("user_name", "" + getMDatabind().withName.getInputText());
                hashMap.put("id_card_front", "" + id_card_front);
//                hashMap.put("id_card_back", "");
                hashMap.put("sex", "" + (sexPosition + 1));
                hashMap.put("id_number", "" + getMDatabind().withIdCard.getInputText());
                hashMap.put("birthday", "" + getMDatabind().withBirthday.getTvRight());
                hashMap.put("city_id", "" + cityId);
                hashMap.put("address", "" + getMDatabind().withCity2.getTvRight());
                hashMap.put("id_card_start_date", "" + getMDatabind().withIdCardStartTime.getTvRight());
                hashMap.put("id_card_end_date", "" + getMDatabind().withIdCardEndTime.getTvRight());
                hashMap.put("marriage_status", "" + (marriagePosition + 1));
                hashMap.put("nation_id", "" + nationId);

                if (TextUtils.isEmpty(uuid) && type == 0 || type == 2) {//1是草稿 0、2 是新建
                    mViewModel.requestIDCardMembers(hashMap);
                } else {
                    hashMap.put("op_type", "identity");
                    hashMap.put("uuid", uuid);
                    mViewModel.requestUpdateMembers(hashMap, AddProjectActivity.ID_CARD, type);
                }
            }
        });

    }

    /**
     * 上传图片
     */
    private void uploadPic(String path) {
        LoadingDialogExtKt.showLoadingExt(this, "上传中");
        UploadFileHelper.getInstance().uploadPictures(getActivity(), path, UploadFileHelper.PATH_HEADER_PERSONNEL, new UploadFileHelper.UploadListener() {
            @Override
            public void onUploadSuccess(String response) {
                LogExtKt.logE("最后回调到的图片---> " + response, "");
                id_card_front = response;
                mViewModel.requestIDCardInfo(response);
                LoadingDialogExtKt.dismissLoadingExt(IdCardFragment.this);
            }

            @Override
            public void onUploadFailed(String error) {
                ToastUtil.show("上传失败");
                LoadingDialogExtKt.dismissLoadingExt(IdCardFragment.this);
            }

            @Override
            public void onUploadProgress(int progress) {

            }


        });
    }

    /**
     * @param datas
     */
    private void showNationDialog(List<BaseIDNameEntity> datas) {
        CommonUtils.showDialogWheelSingleList(getActivity(), "请选择民族", getArrayListString(datas), nation, new OnDialogSelectListener() {
            @Override
            public void onSelect(int position, String text) {
                nation = text;
                nationId = datas.get(position).getId();
                getMDatabind().withNation.setTvRightText(text);
            }
        });
    }

    private String fillHomeTownAndCity(String homeTown, String city, String area) {
        StringBuilder sb = new StringBuilder();
        if (!TextUtils.isEmpty(homeTown)) {
            sb.append(homeTown);
        }

        if (!TextUtils.isEmpty(city) && !city.equals(homeTown)) {
            sb.append(city);
        }
        if (!TextUtils.isEmpty(area)) {
            sb.append(area);
        }
        return sb.toString();
    }

    @Override
    public void onRequestSuccess() {
        getMViewModel().getIdCardInfo().observe(this, new Observer<IDCardMemberEntity>() {
            @Override
            public void onChanged(IDCardMemberEntity idCardMemberEntity) {
                ToastUtil.show("创建成功");
                App.appViewModelInstance.getCreateUuid().setValue(idCardMemberEntity.getUuid());
                App.appViewModelInstance.getProjectPersonnel().setValue(1);
            }
        });

        getMViewModel().getUpdateIDCardStatus().observe(this, new Observer<IDCardMemberEntity>() {
            @Override
            public void onChanged(IDCardMemberEntity idCardMemberEntity) {
                App.appViewModelInstance.getProjectPersonnel().setValue(1);
            }
        });

        mViewModel.getMembersDetailEntity().observe(this, new Observer<MembersDetailEntity>() {
            @Override
            public void onChanged(MembersDetailEntity membersDetailEntity) {
                uuid = membersDetailEntity.getUuid();
                if ("女".equals(membersDetailEntity.getSex())) {
                    sexAdapter.updateItem(1);
                } else {
                    sexAdapter.updateItem(0);
                }
                fillData(membersDetailEntity.getIdentity());
            }
        });

        //ocr识别
        mViewModel.getOcrIdcardInfo().observe(this, new Observer<OCRIDCardInfoEntity>() {
            @Override
            public void onChanged(OCRIDCardInfoEntity ocridCardInfoEntity) {
                if (ocridCardInfoEntity != null) {
                    fillIDCardInfo(ocridCardInfoEntity);
                }
            }
        });
    }

    /**
     * 身份证
     *
     * @param ocridCardInfoEntity
     */
    private void fillIDCardInfo(OCRIDCardInfoEntity ocridCardInfoEntity) {
        if (ocridCardInfoEntity != null) {
            getMDatabind().withName.setInputText(ocridCardInfoEntity.getName());
            getMDatabind().withIdCard.setInputText(ocridCardInfoEntity.getId_number());
            getMDatabind().withCity2.setInputText(ocridCardInfoEntity.getAddress());
            getMDatabind().withBirthday.setTvRightText(ocridCardInfoEntity.getBirthday());
            getMDatabind().withNation.setTvRightText(ocridCardInfoEntity.getNation());
            if ("女".equals(ocridCardInfoEntity.getSex())) {
                sexAdapter.updateItem(1);
            } else {
                sexAdapter.updateItem(0);
            }
            getNationId();
            if (!TextUtils.isEmpty(ocridCardInfoEntity.getHometown()) && !TextUtils.isEmpty(ocridCardInfoEntity.getHometown_city())) {
                getMDatabind().withCity1.setTvRightText(ocridCardInfoEntity.getHometown() + ocridCardInfoEntity.getHometown_city());
                getCityID(ocridCardInfoEntity.getHometown(), ocridCardInfoEntity.getHometown_city());
            }
        }
    }


    private void fillData(IdentityEntity identity) {
        if (identity != null) {
            cityId = identity.getCity_id();
            if (identity.getPic_list().size() > 0) {
                id_card_front = identity.getPic_list().get(0).getSource_url();
                if (!TextUtils.isEmpty(id_card_front)) {
                    GlideUtil.loadPic(getActivity(), id_card_front, getMDatabind().ivCard1);
                }
            }
            getMDatabind().withName.setInputText(identity.getUser_name());
            getMDatabind().withIdCard.setInputText(identity.getId_number());
            getMDatabind().withBirthday.setTvRightText(identity.getBirthday());
            getMDatabind().withCity1.setTvRightText(identity.getCity_name());
            getMDatabind().withCity2.setInputText(identity.getAddress());
            getMDatabind().withIdCardStartTime.setTvRightText(identity.getId_card_start_date());
            getMDatabind().withIdCardEndTime.setTvRightText(identity.getId_card_end_date());
            if ("1".equals(identity.getMarriage_status())) {
                marriagePosition = 0;
                marriageAdapter.updateItem(marriagePosition);
            } else if ("2".equals(identity.getMarriage_status())) {
                marriagePosition = 1;
                marriageAdapter.updateItem(marriagePosition);
            } else if ("3".equals(identity.getMarriage_status())) {
                marriagePosition = 2;
                marriageAdapter.updateItem(marriagePosition);
            }
            nationId = identity.getNation_id();
            getMDatabind().withNation.setTvRightText(identity.getNation_name());
        }
    }


    private void getCityID(String citys, String hometown) {
        final String cityDataJson = MMKVHelper.getString(ConstantMMVK.PROVICE_CITY_AREA_DATA);
        if (!TextUtils.isEmpty(cityDataJson)) {
            List<ProviceCityAreaData> cityDatas = JSON.parseArray(cityDataJson, ProviceCityAreaData.class);
            for (ProviceCityAreaData city : cityDatas) {
                if (citys.equals(city.getName())) {
                    for (int i = 0; i < city.getList().size(); i++) {
                        LogExtKt.logE("" + city.getList().get(i).getName(), "");
                        if (hometown.equals(city.getList().get(i).getName())) {
                            cityId = city.getList().get(i).getId();
                            break;
                        }
                    }
                    break;
                }
            }
        } else {
            AsyncRequestUtil.requestProviceCityArea(new ProviceCityAreaDataCallBack() {
                @Override
                public void cityDataCallBack(List<ProviceCityAreaData> list) {
                    for (ProviceCityAreaData city : list) {
                        if (citys.equals(city.getName())) {
                            for (int i = 0; i < city.getList().size(); i++) {
                                LogExtKt.logE("" + city.getList().get(i).getName(), "");
                                if (hometown.equals(city.getList().get(i).getName())) {
                                    cityId = city.getList().get(i).getId();
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
            });
        }
    }

    private void getNationId() {
        final String cityDataJson = MMKVHelper.getString(ConstantMMVK.NATION_LIST);
        if (!TextUtils.isEmpty(cityDataJson)) {
            List<BaseIDNameEntity> datas = JSON.parseArray(cityDataJson, BaseIDNameEntity.class);
            for (int i = 0; i < datas.size(); i++) {
                if (datas.get(i).getName().contains(getMDatabind().withNation.getTvRight())) {
                    nationId = datas.get(i).getId();
                }
                break;
            }
        } else {
            AsyncRequestUtil.requestNationData(new OnNationListener() {
                @Override
                public void nationCallBack(List<BaseIDNameEntity> datas) {
                    for (int i = 0; i < datas.size(); i++) {
                        if (datas.get(i).getName().contains(getMDatabind().withNation.getTvRight())) {
                            nationId = datas.get(i).getId();
                        }
                        break;
                    }
                }
            });
        }
    }

    private ArrayList<String> getArrayListString(List<BaseIDNameEntity> list) {
        ArrayList<String> names = new ArrayList<>();
        for (BaseIDNameEntity item : list) {
            names.add(item.getName());
        }
        return names;
    }
}
